using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using tafei_thingsapi.Services;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
namespace tafei_thingsapi.Middleware
{
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<JwtMiddleware> _logger;

        public JwtMiddleware(RequestDelegate next, ILogger<JwtMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            // 检查端点是否标记了 AllowAnonymous
            var endpoint = context.GetEndpoint();
            if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
            {
                await _next(context);
                return;
            }
            _logger.LogInformation("JwtMiddleware {Path}", context.Request.Path);

            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            if (token == null)
            {
                token = context.Request.Query["token"].ToString();
            }

            if (token != null)
            {
                var jwtService = context.RequestServices.GetRequiredService<JwtService>();
                var principal = jwtService.ValidateToken(token);

                if (principal != null)
                {
                    context.User = principal;
                    await _next(context);
                    return;
                }
            }
            
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await _next(context);
        }
    }
}